package com.qd.panda.card.collect;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedissonLockTemplate;
import com.cdqidi.util.page.PageUtil;
import com.qd.common.panda.domain.entity.card.collect.CollectCardDTO;
import com.qd.common.panda.domain.entity.card.collect.CollectCardRelationDTO;
import com.qd.common.panda.domain.entity.card.collect.ReceiveCardDTO;
import com.qd.common.panda.domain.entity.card.collect.ReceiveCardsDTO;
import com.qd.common.sys.enums.BaseTableEnum;
import com.qd.common.sys.enums.RemoteEnum;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.panda.service.card.collect.CollectCardHolderService;
import com.qd.panda.service.card.collect.CollectCardService;
import com.qd.panda.service.card.collect.ReceiveCardService;
import com.qd.system.service.dict.MbUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.time.LocalDate;

/**
 * 优惠券/APP_领券
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/app/collectCard/")
@Slf4j
public class AppCollectCardController {
    private final ReceiveCardService receiveCardService;
    private final CollectCardService collectCardService;
    private final CollectCardHolderService collectCardHolderService;

    /**
     * 列表
     *
     * @param dto 查询参数以及页数和每页显示条数
     * @return 列表信息
     */
    @GetMapping(value = "/page")
    public IPage<CollectCardRelationDTO> page(CollectCardRelationDTO dto) {
        if (!StringUtils.hasLength(dto.getPromotionCode()) && !StringUtils.hasLength(dto.getCid())) {
            throw new ApiException(ApiResultWrapper.NULL_ERROR, "推广码或者领劵ID不能为空");
        }
        if (StringUtils.hasLength(dto.getPromotionCode())) {
            if (MbUtil.isNotExists(dto.getPromotionCode(), BaseTableEnum.PROMOTION_CODE)) {
                throw new ApiException(10004, "推广码值错误");
            }
        }
        return collectCardHolderService.page(PageUtil.buildPage(dto), dto);
    }

    /**
     * 领取优惠券
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @PostMapping(value = "/receiveCard")
    public ApiResultWrapper<Object> receiveCard(@RequestBody ReceiveCardDTO dto) {
        return ApiResult.error("不支持");
//        if (MbUtil.isNotExists(dto.getPromotionCode(), BaseTableEnum.PROMOTION_CODE)) {
//            throw new ApiException(10004, "推广码值错误");
//        }
//        String userId = SecurityUtils.getLoginUser().getUserId();
//        String remote = SecurityUtils.getLoginUser().getRemote();
//        if (!remote.equals(RemoteEnum.MINI_PROGRAM.getCode())) {
//            throw new ApiException("当前用户没有权限访问");
//        }
//        String mobile = SecurityUtils.getLoginUser().getUser().getAppUserExtend().getMobile();
//        receiveCardService.receiveCard(userId,mobile,dto);
//        return ApiResult.success();
    }

    /**
     * 是否领劵
     */
    @GetMapping(value = "/existsCollectCard")
    public ApiResultWrapper<Boolean> existsCollectCard(CollectCardRelationDTO dto) {
        if (!StringUtils.hasLength(dto.getPromotionCode()) && !StringUtils.hasLength(dto.getCid())) {
            throw new ApiException(ApiResultWrapper.NULL_ERROR, "推广码或者领劵ID不能为空");
        }
        if (StringUtils.hasLength(dto.getPromotionCode())) {
            if (MbUtil.isNotExists(dto.getPromotionCode(), BaseTableEnum.PROMOTION_CODE)) {
                throw new ApiException(10004, "推广码值错误");
            }
        }

        boolean b = collectCardHolderService.existsCollectCard(dto.getPromotionCode(), dto.getCid(), LocalDate.now());
        return ApiResult.success(b);
    }

    /**
     * 获取领券详情
     *
     * @param cid 主键
     * @return 记录
     */
    @GetMapping(value = "/getByCid")
    public CollectCardDTO getByCid(@Validated @NotBlank(message = "CID不能为空") String cid) {
        return collectCardService.getByIdDto(cid);
    }

    /**
     * 批量领取优惠券
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @PostMapping(value = "/receiveCards")
    public ApiResultWrapper<Object> receiveCards(@RequestBody ReceiveCardsDTO dto) {
        if (MbUtil.isNotExists(dto.getPromotionCode(), BaseTableEnum.PROMOTION_CODE)) {
            throw new ApiException(10004, "推广码值错误");
        }
        String userId = SecurityUtils.getLoginUser().getUserId();
        String remote = SecurityUtils.getLoginUser().getRemote();
        if (!remote.equals(RemoteEnum.MINI_PROGRAM.getCode())) {
            throw new ApiException("当前用户没有权限访问");
        }
        String mobile = SecurityUtils.getLoginUser().getUser().getAppUserExtend().getMobile();
        //加锁
        RedissonLockTemplate.execute(dto.getCid(), () -> {
            receiveCardService.receiveCards(userId, mobile, dto);
            return null;
        }, 60, -1);
        return ApiResult.success();
    }

    /**
     * 根据推广码值获取最新优惠券详情
     *
     * @param promotionCode 推广码值
     * @return 记录
     */
    @GetMapping(value = "/getByPromotionCode")
    public CollectCardDTO getByPromotionCode(@Validated @NotBlank(message = "推广码值错误") String promotionCode) {
        if (MbUtil.isNotExists(promotionCode, BaseTableEnum.PROMOTION_CODE)) {
            throw new ApiException(10004, "推广码值错误");
        }
        return collectCardService.getByPromotionCode(promotionCode);
    }
}